
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author lupo
 */
public class MainMenu extends javax.swing.JFrame {

    short capada, lazos;
    boolean canShuffle = false;
    short currentLazo;
    boolean isOpen = true;
    
    /**
     * Creates new form MainMenu
     */
    
    MyTableModel contestantsTableModel;
    ObjectContainer db;
    
    public MainMenu() {
        // Open/Create the database
        db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "sierragrande.lienzo");
        contestantsTableModel = new MyTableModel();
        contestantsTableModel.addColumn("ID");
        contestantsTableModel.addColumn("Nombre");
        contestantsTableModel.addColumn("Tipo");
        contestantsTableModel.addColumn("Número");
        initComponents();
        
        //Set table headers font and sizes
        contestantsTable.getTableHeader().setFont(new java.awt.Font("Tahoma", 0, 18));
        contestantsTable.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);
        contestantsTable.getTableHeader().getColumnModel().getColumn(0).setPreferredWidth(0);
        contestantsTable.getTableHeader().getColumnModel().getColumn(1).setPreferredWidth(470);
        contestantsTable.getTableHeader().getColumnModel().getColumn(2).setPreferredWidth(200);
        contestantsTable.getTableHeader().getColumnModel().getColumn(3).setPreferredWidth(200);
        
        //Set table renderer for centering information
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i=0; i<contestantsTable.getColumnCount();i++){
            contestantsTable.setDefaultRenderer(contestantsTable.getColumnClass(i),renderer);
        }
        
        //Read current tournament data
        List <Tournament> tournaments = db.query(Tournament.class);
        if (tournaments.isEmpty()){
            tournamentNameLabel.setText("Presione + para comenzar");
            //tournamentNameLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
            capadaLabel.setText("Capada:");
            lazosLabel.setText("Lazos:");
            lazadaSpinner.removeAllItems();
        }else{
            tournamentNameLabel.setText(tournaments.get(0).name);
            capadaLabel.setText("Capada: "+tournaments.get(0).capada);
            lazosLabel.setText("Lazos: "+tournaments.get(0).lazos);
            capada = tournaments.get(0).capada;
            lazos = tournaments.get(0).lazos;
            isOpen = tournaments.get(0).isOpen;
            canShuffle = true;
            currentLazo = tournaments.get(0).currentLazo;
            for (int i=0; i< tournaments.get(0).lazos; i++)
                lazadaSpinner.addItem("Lazo #"+(i+1));
            lazadaSpinner.setSelectedIndex(currentLazo-1);
        }
        
        //setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        
        //Disable default tab behavior
        cabeceroNameTField.setFocusTraversalKeysEnabled(false);
        pateroNameTField.setFocusTraversalKeysEnabled(false);
        cabeceroRangeSpinner.setFocusTraversalKeysEnabled(false);
        pateroRangeSpinner.setFocusTraversalKeysEnabled(false);
        saveCabeceroButton.setFocusTraversalKeysEnabled(false);
        savePateroButton.setFocusTraversalKeysEnabled(false);
        registryPanel.setFocusTraversalKeysEnabled(false);
        
        if (!isOpen){
            System.out.println("is open is false o:");
            closeRegistry();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        tournamentPanel = new javax.swing.JPanel();
        tournamentNameLabel = new javax.swing.JLabel();
        capadaLabel = new javax.swing.JLabel();
        lazosLabel = new javax.swing.JLabel();
        goLazadaButton = new javax.swing.JButton();
        resultsButton = new javax.swing.JButton();
        newTournamentButton = new javax.swing.JButton();
        bannerLabel = new javax.swing.JLabel();
        lazadaSpinner = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        registryPanel = new javax.swing.JPanel();
        cabeceroNameTField = new javax.swing.JTextField();
        cabeceroRangeSpinner = new javax.swing.JComboBox();
        saveCabeceroButton = new javax.swing.JButton();
        savePateroButton = new javax.swing.JButton();
        pateroNameTField = new javax.swing.JTextField();
        closeRegistryButton = new javax.swing.JButton();
        pateroRangeSpinner = new javax.swing.JComboBox();
        cabeceroLabel = new javax.swing.JLabel();
        cabeceroLabel1 = new javax.swing.JLabel();
        pateroNameLabel = new javax.swing.JLabel();
        cabeceroNameLabel = new javax.swing.JLabel();
        cabeceroNameLabel1 = new javax.swing.JLabel();
        cabeceroNameLabel2 = new javax.swing.JLabel();
        contestantsPanel = new javax.swing.JPanel();
        searchLabel = new javax.swing.JLabel();
        searchTField = new javax.swing.JTextField();
        eraseButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        contestantsTable = new javax.swing.JTable();
        winnersPanel = new javax.swing.JPanel();
        searchLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lazada Sierra Grande - Lienzo");
        setAutoRequestFocus(false);
        setPreferredSize(new java.awt.Dimension(800, 550));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
        });
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        tabbedPane.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tabbedPaneStateChanged(evt);
            }
        });

        tournamentPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tournamentNameLabel.setFont(new java.awt.Font("Tahoma", 0, 70)); // NOI18N
        tournamentNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        tournamentNameLabel.setText("TORNEO TAL");
        tournamentPanel.add(tournamentNameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 61, 865, -1));

        capadaLabel.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        capadaLabel.setText("Capada: 10");
        tournamentPanel.add(capadaLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 200, -1, -1));

        lazosLabel.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lazosLabel.setText("Lazos: 10");
        tournamentPanel.add(lazosLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 200, -1, -1));

        goLazadaButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        goLazadaButton.setText("Ir");
        goLazadaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goLazadaButtonActionPerformed(evt);
            }
        });
        tournamentPanel.add(goLazadaButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 400, 72, 42));

        resultsButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        resultsButton.setText("Resultados");
        resultsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resultsButtonActionPerformed(evt);
            }
        });
        tournamentPanel.add(resultsButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 360, 142, 47));

        newTournamentButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        newTournamentButton.setText("+");
        newTournamentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newTournamentButtonActionPerformed(evt);
            }
        });
        tournamentPanel.add(newTournamentButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(810, 11, -1, 47));

        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Sierra Grande Banner.png"))); // NOI18N
        bannerLabel.setText("jLabel1");
        bannerLabel.setPreferredSize(new java.awt.Dimension(850, 135));
        tournamentPanel.add(bannerLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 380, 870, 140));

        lazadaSpinner.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        tournamentPanel.add(lazadaSpinner, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 320, 170, 50));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/logo mail.png"))); // NOI18N
        tournamentPanel.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 10, -1, -1));

        tabbedPane.addTab("Torneo", tournamentPanel);

        registryPanel.setName("");
        registryPanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                registryPanelKeyReleased(evt);
            }
        });

        cabeceroNameTField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        cabeceroNameTField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                cabeceroNameTFieldKeyReleased(evt);
            }
        });

        cabeceroRangeSpinner.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        cabeceroRangeSpinner.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "3", "4", "5", "6", "7", "8", "9" }));
        cabeceroRangeSpinner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cabeceroRangeSpinnerActionPerformed(evt);
            }
        });
        cabeceroRangeSpinner.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                cabeceroRangeSpinnerKeyReleased(evt);
            }
        });

        saveCabeceroButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        saveCabeceroButton.setText("Guardar");
        saveCabeceroButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveCabeceroButtonActionPerformed(evt);
            }
        });

        savePateroButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        savePateroButton.setText("Guardar");
        savePateroButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                savePateroButtonActionPerformed(evt);
            }
        });

        pateroNameTField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        pateroNameTField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                pateroNameTFieldKeyReleased(evt);
            }
        });

        closeRegistryButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        closeRegistryButton.setText("Cerrar Inscripciones");
        closeRegistryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeRegistryButtonActionPerformed(evt);
            }
        });

        pateroRangeSpinner.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        pateroRangeSpinner.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "3", "4", "5", "6", "7", "8", "9" }));
        pateroRangeSpinner.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                pateroRangeSpinnerKeyReleased(evt);
            }
        });

        cabeceroLabel.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
        cabeceroLabel.setText("Cabecero");

        cabeceroLabel1.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
        cabeceroLabel1.setText("Patero");

        pateroNameLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        pateroNameLabel.setText("Nombre:");

        cabeceroNameLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        cabeceroNameLabel.setText("Nombre:");

        cabeceroNameLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        cabeceroNameLabel1.setText("Número:");

        cabeceroNameLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        cabeceroNameLabel2.setText("Número:");

        javax.swing.GroupLayout registryPanelLayout = new javax.swing.GroupLayout(registryPanel);
        registryPanel.setLayout(registryPanelLayout);
        registryPanelLayout.setHorizontalGroup(
            registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(113, 113, 113)
                .addComponent(cabeceroLabel)
                .addGap(275, 275, 275)
                .addComponent(cabeceroLabel1))
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addComponent(cabeceroNameLabel)
                .addGap(331, 331, 331)
                .addComponent(pateroNameLabel))
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addComponent(cabeceroNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(73, 73, 73)
                .addComponent(pateroNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(109, 109, 109)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cabeceroNameLabel1)
                    .addComponent(cabeceroRangeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(141, 141, 141)
                .addComponent(closeRegistryButton)
                .addGap(127, 127, 127)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cabeceroNameLabel2)
                    .addGroup(registryPanelLayout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(pateroRangeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(117, 117, 117)
                .addComponent(saveCabeceroButton, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(262, 262, 262)
                .addComponent(savePateroButton, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        registryPanelLayout.setVerticalGroup(
            registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(registryPanelLayout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cabeceroLabel)
                    .addComponent(cabeceroLabel1))
                .addGap(24, 24, 24)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(registryPanelLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(cabeceroNameLabel))
                    .addComponent(pateroNameLabel))
                .addGap(8, 8, 8)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cabeceroNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pateroNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(73, 73, 73)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(registryPanelLayout.createSequentialGroup()
                        .addComponent(cabeceroNameLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(cabeceroRangeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(closeRegistryButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(registryPanelLayout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(cabeceroNameLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(pateroRangeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(47, 47, 47)
                .addGroup(registryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saveCabeceroButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(savePateroButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        tabbedPane.addTab("Registro", registryPanel);

        searchLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        searchLabel.setText("Buscar:");

        searchTField.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        searchTField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                searchTFieldKeyTyped(evt);
            }
        });

        eraseButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        eraseButton.setText("Borrar");
        eraseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eraseButtonActionPerformed(evt);
            }
        });

        contestantsTable.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        contestantsTable.setModel(contestantsTableModel);
        contestantsTable.setRowHeight(25);
        jScrollPane1.setViewportView(contestantsTable);

        javax.swing.GroupLayout contestantsPanelLayout = new javax.swing.GroupLayout(contestantsPanel);
        contestantsPanel.setLayout(contestantsPanelLayout);
        contestantsPanelLayout.setHorizontalGroup(
            contestantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contestantsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 850, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(contestantsPanelLayout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(searchLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchTField, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(eraseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(68, 68, 68))
        );
        contestantsPanelLayout.setVerticalGroup(
            contestantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contestantsPanelLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(contestantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchLabel)
                    .addComponent(searchTField, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
                    .addComponent(eraseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35))
        );

        tabbedPane.addTab("Participantes", contestantsPanel);

        searchLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        searchLabel1.setText("Para adquirir esta funcionalidad, por favor comúniquese con Lienzo");

        javax.swing.GroupLayout winnersPanelLayout = new javax.swing.GroupLayout(winnersPanel);
        winnersPanel.setLayout(winnersPanelLayout);
        winnersPanelLayout.setHorizontalGroup(
            winnersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, winnersPanelLayout.createSequentialGroup()
                .addContainerGap(84, Short.MAX_VALUE)
                .addComponent(searchLabel1)
                .addGap(72, 72, 72))
        );
        winnersPanelLayout.setVerticalGroup(
            winnersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(winnersPanelLayout.createSequentialGroup()
                .addGap(237, 237, 237)
                .addComponent(searchLabel1)
                .addContainerGap(273, Short.MAX_VALUE))
        );

        tabbedPane.addTab("Ganadores", winnersPanel);

        getContentPane().add(tabbedPane);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-886)/2, (screenSize.height-589)/2, 886, 589);
    }// </editor-fold>//GEN-END:initComponents

    private void saveCabeceroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCabeceroButtonActionPerformed
        //Get next corresponding id
        if(cabeceroNameTField.getText().length() != 0){
            List<Contestant> contestants = db.query(Contestant.class);
            int id=0;
            for (int i=0; i<contestants.size(); i++)
                if (id<contestants.get(i).id)
                    id = contestants.get(i).id;
            //Save a new Cabecero in the DB
            db.store(new Cabecero(id+1, cabeceroNameTField.getText(), Short.parseShort((String)cabeceroRangeSpinner.getSelectedItem())));
            cabeceroNameTField.setText("");
            cabeceroRangeSpinner.setName("3");
            pateroNameTField.setText("");
            pateroRangeSpinner.setName("3");
        // pateroRangeSpinner.setValue((int)3);
            db.commit();
        }
        else{
            Component frame = null;
            JOptionPane.showMessageDialog(frame,
            "Ingrese Nombre!","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
            
        }
    }//GEN-LAST:event_saveCabeceroButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        //Finalize application
        //Close database
        db.close();
    }//GEN-LAST:event_formWindowClosed

    private void tabbedPaneStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabbedPaneStateChanged
        //Detect what tab has been pressed
        JTabbedPane tp = (JTabbedPane)evt.getSource();
        if (tp.getSelectedIndex()==2){
            //We are in Contestants tab. Fill the table
            fillContestantsTable();
        }
    }//GEN-LAST:event_tabbedPaneStateChanged

    private void savePateroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savePateroButtonActionPerformed
        //Get next corresponding id
        if(pateroNameTField.getText().length() != 0){
            List<Contestant> contestants = db.query(Contestant.class);
            int id=0;
            for (int i=0; i<contestants.size(); i++)
                if (id<contestants.get(i).id)
                    id = contestants.get(i).id;
            //Save a new Cabecero in the DB
            db.store(new Patero(id+1, pateroNameTField.getText(), Short.parseShort((String)pateroRangeSpinner.getSelectedItem())));
            pateroNameTField.setText("");
            pateroRangeSpinner.setName("3");
            cabeceroNameTField.setText("");
            cabeceroRangeSpinner.setName("3");
            db.commit();
        }
        else{
            Component frame = null;
            JOptionPane.showMessageDialog(frame,
            "Ingrese Nombre!","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
            
        }
    }//GEN-LAST:event_savePateroButtonActionPerformed

    private void newTournamentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newTournamentButtonActionPerformed
        Object[] options = {"Sí", "No"};
        Component frame = null;
        int n = JOptionPane.showOptionDialog(frame,
            "¿Estas seguro? Toda la informacion del torneo anterior se perderá",
            "Lazada Sierra Grande - Lienzo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, options, options[1]);
        if (n==0){
            //Create a NewTourament JFrame
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setVisible(false);
                    new NewTournament(MainMenu.this).setVisible(true);
                }
            });
        }
    }//GEN-LAST:event_newTournamentButtonActionPerformed

    private void searchTFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTFieldKeyTyped
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (searchTField.getText().contentEquals(""))
                    fillContestantsTable();
                else{
                    //Update the table to show only the contestants fit the search
                    List <Contestant> result = db.query(new Predicate<Contestant>() {
                            @Override
                            public boolean match(Contestant pilot) {
                                return pilot.getName().toLowerCase().contains(
                                        searchTField.getText().toLowerCase());
                            }
                    });
                    fillContestantsTable(result);
                }
            }
        });
    }//GEN-LAST:event_searchTFieldKeyTyped

    private void eraseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eraseButtonActionPerformed
        int selectedRows[] = contestantsTable.getSelectedRows();
        if (selectedRows.length > 0){ //if there are selected contestants
            //Custom button text
            Object[] options = {"Sí", "No"};
            Component frame = null;
            int n = JOptionPane.showOptionDialog(frame,
                "¿Estas seguro de que deseas eliminar a los participantes?",
                "Lazada Sierra Grande - Lienzo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, options, options[1]);

            if (n==0){
                // Erase all the selected rows
                for (int i=0; i<selectedRows.length; i++){
                    //Get noContestant
                    int id = (int) contestantsTable.getValueAt(selectedRows[i], 0);
                    //Delete the contestant from the db
                    ObjectSet result = db
                        .queryByExample(new Contestant(id, null, (short)0));
                    Contestant found = (Contestant) result.next();
                    db.delete(found);
                }
                fillContestantsTable();//Show changes on table
                searchTField.setText("");
                db.commit();
            }
        }
    }//GEN-LAST:event_eraseButtonActionPerformed

    private void registryPanelKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_registryPanelKeyReleased
        // TODO add your handling code here:
        int key = evt.getKeyCode();
     if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_TAB) {
      
         
       ((Component) evt.getSource()).transferFocus();;
        }
    }//GEN-LAST:event_registryPanelKeyReleased

    private void cabeceroNameTFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cabeceroNameTFieldKeyReleased
        // TODO add your handling code here:
        
        int key = evt.getKeyCode();
     if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_TAB) {
        
          if(cabeceroNameTField.getText().length() == 0){
                pateroNameTField.requestFocusInWindow();
          }
           else{
             //cabeceroRangeSpinner.requestFocusInWindow();
              cabeceroRangeSpinner.requestFocusInWindow();
           }
     }
    }//GEN-LAST:event_cabeceroNameTFieldKeyReleased

    private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
        // TODO add your handling code here:
      
    }//GEN-LAST:event_formKeyReleased

    private void pateroNameTFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pateroNameTFieldKeyReleased
        // TODO add your handling code here:
        
        int key = evt.getKeyCode();
     if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_TAB) {
        
         
         if(pateroNameTField.getText().length() == 0){
                cabeceroNameTField.requestFocusInWindow();
          }
           else{
              pateroRangeSpinner.requestFocusInWindow();
           }
             
             
             
       
        }
    }//GEN-LAST:event_pateroNameTFieldKeyReleased

    private void cabeceroRangeSpinnerKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cabeceroRangeSpinnerKeyReleased
        // TODO add your handling code here:
        int key = evt.getKeyCode();
       
     if (key == KeyEvent.VK_ENTER) {
      
        
         
         if(cabeceroNameTField.getText().length() != 0){
            List<Contestant> contestants = db.query(Contestant.class);
            int id=0;
            for (int i=0; i<contestants.size(); i++)
                if (id<contestants.get(i).id)
                    id = contestants.get(i).id;
            //Save a new Cabecero in the DB
            db.store(new Cabecero(id+1, cabeceroNameTField.getText(), Short.parseShort((String)cabeceroRangeSpinner.getSelectedItem())));
            cabeceroNameTField.setText("");
            cabeceroRangeSpinner.setName("3");
            pateroNameTField.setText("");
            pateroRangeSpinner.setName("3");
            pateroNameTField.requestFocusInWindow();
            db.commit();
        }
        else{
            Component frame = null;
            JOptionPane.showMessageDialog(frame,
            "Ingrese Nombre!","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
            cabeceroNameTField.requestFocusInWindow();
            
        }
        }
    }//GEN-LAST:event_cabeceroRangeSpinnerKeyReleased

    private void pateroRangeSpinnerKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pateroRangeSpinnerKeyReleased
        // TODO add your handling code here:
        int key = evt.getKeyCode();
     if (key == KeyEvent.VK_ENTER) {
        
        
        if(pateroNameTField.getText().length() != 0){
            List<Contestant> contestants = db.query(Contestant.class);
            int id=0;
            for (int i=0; i<contestants.size(); i++)
                if (id<contestants.get(i).id)
                    id = contestants.get(i).id;
            //Save a new Cabecero in the DB
            db.store(new Patero(id+1, pateroNameTField.getText(), Short.parseShort((String)pateroRangeSpinner.getSelectedItem())));
            pateroNameTField.setText("");
            pateroRangeSpinner.setName("3");
            cabeceroNameTField.setText("");
            cabeceroRangeSpinner.setName("3");
            cabeceroNameTField.requestFocusInWindow();
            db.commit();
        }
        else{
            Component frame = null;
            JOptionPane.showMessageDialog(frame,
            "Ingrese Nombre!","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
            pateroNameTField.requestFocusInWindow();
            
        }
        }
    }//GEN-LAST:event_pateroRangeSpinnerKeyReleased

    private void goLazadaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goLazadaButtonActionPerformed
        if (canShuffle){
            //Tournament has been created and we can launch lazos
            
            if (!isOpen){
                //Tournament registry has been closed and can begin

                //Check if this lazo can be run
                List<Tournament> tournaments = db.query(Tournament.class);
                Tournament tournament = tournaments.get(0);
                if (lazadaSpinner.getSelectedIndex()+1 <= tournament.currentLazo){
                    //Create a NewTourament JFrame
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            setVisible(false);
                            LazadaWindow lazadaWindow = new LazadaWindow(MainMenu.this, (short)(lazadaSpinner.getSelectedIndex()+1));
                            lazadaWindow.setTitle((String)lazadaSpinner.getSelectedItem());
                            lazadaWindow.setVisible(true);
                        }
                    });
                }else{
                    Component frame = null;
                    JOptionPane.showMessageDialog(frame,
                    "Es necesario crear los lazos anteriores antes de ir al "+(String)lazadaSpinner.getSelectedItem(),"Lazada Sierra Grande - Lienzo",
                    JOptionPane.PLAIN_MESSAGE);
                }
            }
            else{
                Component frame = null;
                JOptionPane.showMessageDialog(frame,
                    "Debe cerrar las inscripciones para comenzar. Haga click en el botón \"Cerrar Inscripciones\" "
                        + "de la pestaña \"Registro\"","Lazada Sierra Grande - Lienzo",
                    JOptionPane.PLAIN_MESSAGE);
            }
        }else{
            Component frame = null;
            JOptionPane.showMessageDialog(frame,
            "Por favor primero cree un nuevo torneo. Presione el botón + para comenzar","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
        }
    }//GEN-LAST:event_goLazadaButtonActionPerformed

    private void cabeceroRangeSpinnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cabeceroRangeSpinnerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cabeceroRangeSpinnerActionPerformed

    private void closeRegistryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeRegistryButtonActionPerformed
        // Show are you sure dialog
        Object[] options = {"Sí", "No"};
        Component frame = null;
        int n = JOptionPane.showOptionDialog(frame,
            "¿Estas seguro? Despues de cerrar las inscripciones no se podrán añadir, "
                + "modificar ni eliminar participantes",
            "Lazada Sierra Grande - Lienzo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, options, options[1]);
        if (n==0){
            isOpen = false;
            closeRegistry();
            List<Tournament> tournaments = db.query(Tournament.class);
            Tournament tournament = tournaments.get(0);
            tournament.setIsOpen(false);
            db.store(tournament);
            db.commit();
        }
    }//GEN-LAST:event_closeRegistryButtonActionPerformed

    private void resultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultsButtonActionPerformed
        Component frame = null;
        JOptionPane.showMessageDialog(frame,
            "Para adquirir esta funcionalidad por favor comúniquese con Lienzo","Lazada Sierra Grande - Lienzo",
            JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_resultsButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainMenu().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JLabel cabeceroLabel;
    private javax.swing.JLabel cabeceroLabel1;
    private javax.swing.JLabel cabeceroNameLabel;
    private javax.swing.JLabel cabeceroNameLabel1;
    private javax.swing.JLabel cabeceroNameLabel2;
    private javax.swing.JTextField cabeceroNameTField;
    private javax.swing.JComboBox cabeceroRangeSpinner;
    public javax.swing.JLabel capadaLabel;
    private javax.swing.JButton closeRegistryButton;
    private javax.swing.JPanel contestantsPanel;
    private javax.swing.JTable contestantsTable;
    private javax.swing.JButton eraseButton;
    private javax.swing.JButton goLazadaButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JComboBox lazadaSpinner;
    private javax.swing.JLabel lazosLabel;
    private javax.swing.JButton newTournamentButton;
    private javax.swing.JLabel pateroNameLabel;
    private javax.swing.JTextField pateroNameTField;
    private javax.swing.JComboBox pateroRangeSpinner;
    private javax.swing.JPanel registryPanel;
    private javax.swing.JButton resultsButton;
    private javax.swing.JButton saveCabeceroButton;
    private javax.swing.JButton savePateroButton;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JLabel searchLabel1;
    private javax.swing.JTextField searchTField;
    private javax.swing.JTabbedPane tabbedPane;
    public javax.swing.JLabel tournamentNameLabel;
    private javax.swing.JPanel tournamentPanel;
    private javax.swing.JPanel winnersPanel;
    // End of variables declaration//GEN-END:variables

    public void fillContestantsTable(){
        //Clear the table
        contestantsTableModel.setNumRows(0);
        //Fill the table with the contestants
        List <Contestant> contestants = db.query(Contestant.class);
        for (int i=0; i<contestants.size(); i++){
            Object[] contestant = {contestants.get(i).id, contestants.get(i).name,
            contestants.get(i).getClass().getName(), contestants.get(i).range};
            contestantsTableModel.addRow(contestant);
        }
    }
    
    public void fillContestantsTable(List<Contestant> contestants){
        //Clear the table
        contestantsTableModel.setNumRows(0);
        //Fill the table with the contestants
        for (int i=0; i<contestants.size(); i++){
            Object[] contestant = {contestants.get(i).id, contestants.get(i).name,
            contestants.get(i).getClass().getName(), contestants.get(i).range};
            contestantsTableModel.addRow(contestant);
        }
    }
    
    public void createNewTournament(String name, short capada, short lazos){
        //Erase previous tournament
        List<Tournament> tournament = db.query(Tournament.class);
        for (int i=0; i<tournament.size(); i++)
            db.delete(tournament.get(i));
        //Store new one
        db.store(new Tournament(name, capada, lazos));
        //Refresh tournament displaying info
        tournamentNameLabel.setText(name);
        capadaLabel.setText("Capada: "+Short.toString(capada));
        lazosLabel.setText("Lazos: "+Short.toString(lazos));
        db.commit();
    }
    
    private void closeRegistry(){
        cabeceroNameTField.setEnabled(false);
        pateroNameTField.setEnabled(false);
        cabeceroRangeSpinner.setEnabled(false);
        pateroRangeSpinner.setEnabled(false);
        saveCabeceroButton.setEnabled(false);
        savePateroButton.setEnabled(false);
        eraseButton.setEnabled(false);
        closeRegistryButton.setEnabled(false);
    }
    
    public void openRegistry(){
        cabeceroNameTField.setEnabled(true);
        pateroNameTField.setEnabled(true);
        cabeceroRangeSpinner.setEnabled(true);
        pateroRangeSpinner.setEnabled(true);
        saveCabeceroButton.setEnabled(true);
        savePateroButton.setEnabled(true);
        eraseButton.setEnabled(true);
        closeRegistryButton.setEnabled(true);
    }
    
    class MyTableModel extends DefaultTableModel {
        
        MyTableModel(){
            super();
        }
        
        @Override
        public boolean isCellEditable(int row, int cols){
            if (isOpen){
                if(cols==1 || cols==3)
                    return true;
                return false;
            }else
                return false;
        }
        
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex==3)
                return Integer.class;
            else
                return String.class;
        };
        
        @Override
        public void setValueAt(Object val, int rowIndex, int columnIndex) {
            if (columnIndex==3){
                int range = (int)val;
                if (range<3 || range>9)
                    contestantsTable.getCellEditor().cancelCellEditing();
                else{
                    super.setValueAt(val, rowIndex, columnIndex);
                    //Save the contestant's new range in the db
                    ObjectSet result = db.queryByExample(new Contestant(
                            rowIndex+1,null,(short)0));
                    Contestant contestant = (Contestant) result.next();
                    contestant.setRange((short)range);
                    db.store(contestant);
                    db.commit();
                }
            }
            else if (columnIndex==1){
                String name = (String)val;
                super.setValueAt(val, rowIndex, columnIndex);
                //Save the contestant's new name in the db
                ObjectSet result = db.queryByExample(new Contestant(
                    rowIndex+1,null,(short)0));
                Contestant contestant = (Contestant) result.next();
                contestant.setName(name);
                db.store(contestant);
                db.commit();
            }
        }
    }
}
